package p_stack_queue;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description: 用队列实现栈
 * User: 王圆豪
 * Date: 2024-08-16
 * Time: 23:24
 */
//class Main{
//    public static void main(String[] args) {
//        Q_stack q_stack = new Q_stack();
//        q_stack.push(1);
//        q_stack.push(2);
//        q_stack.push(3);
//        System.out.println(q_stack.top());
//    }
//}
public class Q_stack {
    Queue<Integer> queue1;
    Queue<Integer> queue2;
    public Q_stack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }

    public void push(int x) {
        if (empty()) {
            queue1.offer(x);
        }else if (!queue2.isEmpty()) {
            queue2.offer(x);
        }else {
            queue1.offer(x);
        }
    }

    public int pop() {
        if (empty()) {
            return -1;
        }else if (!queue2.isEmpty()) {
            for (int i = 0; i < queue2.size() + queue1.size() - 1; i++) {
                queue1.offer(queue2.poll());
            }
            return queue2.remove();
        }else {
            for (int i = 0; i < queue1.size() + queue2.size() - 1; i++) {
                queue2.offer(queue1.poll());
            }
            return queue1.remove();
        }
    }

    public int top() {
        int k = 0;
        if (empty()) {
            return -1;
        }else if (!queue2.isEmpty()) {
            for (int i = 0; i < queue2.size() + queue1.size(); i++) {
                k = queue2.element();
                queue1.offer(queue2.poll());
            }
            return k;
        }else {
            for (int i = 0; i < queue1.size() + queue2.size(); i++) {
                k = queue1.element();
                queue2.offer(queue1.poll());
            }
            return k;
        }
    }

    public boolean empty() {
        return queue1.isEmpty() && queue2.isEmpty();
    }
}
